package com.xyd.Servlet;

import com.xyd.Biz.CommodityBiz;
import com.xyd.Biz.Impl.CommodityBizImpl;
import com.xyd.Entity.Commodity;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/ViewCommondityServlet")
public class ViewCommondityServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int commondityId = Integer.parseInt(request.getParameter("commodity_id"));
        setCookieYS(request,response,commondityId);
        CommodityBiz commodityBiz = new CommodityBizImpl();
        Commodity commodity = commodityBiz.SerachCommodityById(commondityId);

        request.setAttribute("commodity",commodity);
        request.getRequestDispatcher("product-view.jsp").forward(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    public void setCookieYS(HttpServletRequest request,HttpServletResponse response, int id){
        Cookie[] cookies= request.getCookies();
        Cookie cookie1 =null;
        Cookie cookie2 =null;
        for (Cookie c :cookies){
            if(c.getName().equals("YSH1")){
                cookie1 = c;
            }else if(c.getName().equals("YSH2")){
                cookie2 = c;
            }
        }
        if(cookie1==null&&cookie2==null){
            cookie1 = new Cookie("YSH1",String.valueOf(id));
            cookie1.setMaxAge(60*60*24);
            response.addCookie(cookie1);
        }else if(cookie1!=null&&cookie2==null){
            String c1 = cookie1.getValue();
            cookie1.setValue(String.valueOf(id));
            cookie2 = new Cookie("YSH2",c1);
            cookie1.setMaxAge(60*60*24);
            cookie2.setMaxAge(60*60*24);
            response.addCookie(cookie1);
            response.addCookie(cookie2);
        }else if(cookie1==null&&cookie2!=null){
            cookie1 = new Cookie("YSH1",String.valueOf(id));
            cookie1.setMaxAge(60*60*24);
            response.addCookie(cookie1);
        }else if(cookie1!=null&&cookie2!=null){
            String c1 = cookie1.getValue();
            cookie1.setValue(String.valueOf(id));
            cookie2.setValue(c1);

            cookie1.setMaxAge(60*60*24);
            cookie2.setMaxAge(60*60*24);
            response.addCookie(cookie1);
            response.addCookie(cookie2);
        }
    }
}
